package cn.iocoder.yudao.module.system.dal.redis.translate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: li
 * Date: 2024/4/1
 */
@Repository
public class TranslateRedisDAO {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public String get(String text, String targetLanguage) {
        final String redisKey = formatKey(text, targetLanguage);
        final String translatedText = stringRedisTemplate.opsForValue().get(redisKey);
        return translatedText;
    }

    public void set(String text, String targetLanguage, String translatedText) {
        if (StrUtil.isEmpty(translatedText)) {
            return;
        }

        final String redisKey = formatKey(text, targetLanguage);
        stringRedisTemplate.opsForValue().set(redisKey, translatedText, 12, TimeUnit.HOURS);
    }

    private static String formatKey(String text, String targetLanguage) {
        final String md5 = SecureUtil.md5(text + targetLanguage);
        return String.format(RedisKeyConstants.TRANSLATE, md5);
    }
}
